<?php

namespace app\admin\controller;

use cmf\controller\AdminBaseController;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\Db;
use think\db\Query;
use think\Request;

class GradeController extends AdminBaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $name = input('name');
        $grade = Db::name('grade g')
            ->join('cmf_subject s','s.id=g.subject_id')
            ->join('cmf_student st','st.id=g.student_id')
            ->where(function (Query $query) use ($name){
                $query->where('g.grade','like',"%$name%");
            })
            ->field('g.*,s.name as subject_name,st.name as student_name')
            ->order('id DESC')
            ->paginate('3',false,['query'=>$this->request->param()]);
        //halt($grade);
        $page = $grade->render();
        return $this->fetch('',['page'=>$page,'grade'=>$grade]);
    }

    /**
     * 显示添加资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function add()
    {
        $subject=Db::name('subject')->select();
        $student = Db::name('student')->select();
        return $this->fetch('',['subject'=>$subject,'student'=>$student]);
    }
    public function addPost()
    {
        if(request()->isPost()){
            if(empty(input('grade'))){
                $this->error('请输入成绩');
            }
            $add = Db::name('grade')->insert(input());
            if($add){
                $this->success('添加成功','grade/index');
                    $this->error('添加失败');
            }
        }
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        $subject=Db::name('subject')->select();
        $student = Db::name('student')->select();
        $grade = Db::name('grade')->get($id);
        return $this->fetch('',['subject'=>$subject,'student'=>$student,'grade'=>$grade]);
    }
    public function editPost()
    {
        if(request()->isPost()){
            //halt(input());
            if(empty(input('grade'))){
                $this->error('请输入成绩');
            }
            $edit = Db::name('grade')->update(input());
            if($edit){
                $this->success('修改成功','grade/index');
                $this->error('修改失败');
            }
        }
    }


    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $del = Db::name('grade')->delete($id);
        if($del)
            $this->success('删除成功','grade/index');
            $this->error('删除失败');
    }

    public function exportExcel()
    {
        // 查询要导出的数据
        $data = Db::name('grade g')
            ->join('cmf_subject s','s.id=g.subject_id')
            ->join('cmf_student st','st.id=g.student_id')
            ->field('g.*,s.name as subject_name,st.name as student_name')
            ->select();
        // 实例化
        $spreadsheet = new Spreadsheet();
        // 获取活动单元格
        $sheet = $spreadsheet->getActiveSheet();

        // 获取单元格
        $cellA = $sheet->getCell('A1');
        // 设置单元格的值
        $cellA->setValue('ID');
        // 设置 A 列 列宽
        $sheet->getColumnDimension('A')->setWidth(10);
        // 设置第一行 行高
        $sheet->getRowDimension(1)->setRowHeight(20);

        $cellB = $sheet->getCell('B1');
        $cellB->setValue('学科名称');
        $sheet->getColumnDimension('B')->setWidth(10);

        $cellC = $sheet->getCell('C1');
        $cellC->setValue('学生姓名');
        $sheet->getColumnDimension('C')->setWidth(10);

        $cellD = $sheet->getCell('D1');
        $cellD->setValue('成绩');
        $sheet->getColumnDimension('D')->setWidth(10);
        // 设置样式 标题
        $styleArray = [
            'alignment' => [
                'horizontal' => 'center', //水平居中
                'vertical' => 'center', //垂直居中
            ],
            'font' => [
                'name' => '黑体',
                'bold' => false,
                'size' => 10
            ]
        ];
        // 设置样式 正文
        $styleArrayBody = [
            'alignment' => [
                'horizontal' => 'center', //水平居中
                'vertical' => 'center', //垂直居中
            ],
            'font' => [
                'name' => '宋体',
                'bold' => false,
                'size' => 10
            ]
        ];
        // 应用样式
        $sheet->getStyle('A1')->applyFromArray($styleArray);
        $sheet->getStyle('B1')->applyFromArray($styleArray);
        $sheet->getStyle('C1')->applyFromArray($styleArray);
        $sheet->getStyle('D1')->applyFromArray($styleArray);

        // 从 A2 开始填充数据
        foreach ($data as $k => $v) {
            $n = $k + 2;
            // 获取单元格
            $cellA = $sheet->getCell('A'.$n);
            // 设置单元格的值
            $cellA->setValue($v['id']);

            $cellB = $sheet->getCell('B'.$n);
            $cellB->setValue($v['subject_name']);

            $cellC = $sheet->getCell('C'.$n);
            $cellC->setValue($v['student_name']);

            $cellD = $sheet->getCell('D'.$n);
            $cellD->setValue($v['grade']);


            // 再给表格体设置样式
            $sheet->getStyle('A'.$n)->applyFromArray($styleArrayBody);
            $sheet->getStyle('B'.$n)->applyFromArray($styleArrayBody);
            $sheet->getStyle('C'.$n)->applyFromArray($styleArrayBody);
            $sheet->getStyle('D'.$n)->applyFromArray($styleArrayBody);
        }

        $file_name = '成绩列表.xlsx';
        // 实例化导出类
        header('Content-Type:application/vnd.ms-excel');
        header('Content-Disposition:attachment;filename='.$file_name);
        header('Cache-Control:max-age=0');

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
    }

    // 从 Excel 导入数据
    public function importExcel()
    {
        // 接收文件
        $file = $_FILES['file']['tmp_name'];
        // 创建读操作
        $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
        // 打开文件、载入excel表格
        $spreadsheet = $reader->load($file);
        // 获取活动工作薄
        $sheet = $spreadsheet->getActiveSheet();

        // 获取总列数
        //$highestColumn = $sheet->getHighestColumn();
        // 获取总行数
        $highestRow = $sheet->getHighestRow();
        // 将列转为数字
        //$highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);

        // 存放插入成功的记录
        $successLog = [];
        // 存放插入失败的记录
        $failLog = [];

        // 从第二行开始读取表格数据，循环写入数据库
        for ($i = 2; $i <= $highestRow; $i++) {
            // 第 1 次循环获取第 2 列 第 2 行单元格的值，第 2 次循环获取第 2 列 第 3 行单元格的值
            $subject_id = $sheet->getCellByColumnAndRow(2,$i)->getValue();
            $student_id = $sheet->getCellByColumnAndRow(3,$i)->getValue();
            $grade = $sheet->getCellByColumnAndRow(4,$i)->getValue();
            $data = [
                'subject_id' => $subject_id,
                'student_id' => $student_id,
                'grade' => $grade,
            ];
            $insert = Db::name('grade')->insert($data);
            if ($insert) {
                $successLog[] = '第'.$i.'条，插入成功';
            } else {
                $failLog[] = '第'.$i.'条，插入失败';
            }
        }
        // 将成功数和失败数返回给 ajax
        return json(['success' => count($successLog), 'fail' => count($failLog)]);
    }

    public function download()
    {
        // 实例化
        $spreadsheet = new Spreadsheet();
        // 获取活动单元格
        $sheet = $spreadsheet->getActiveSheet();

        // 获取单元格
        $cellA = $sheet->getCell('A1');
        // 设置单元格的值
        $cellA->setValue('ID');
        // 设置 A 列 列宽
        $sheet->getColumnDimension('A')->setWidth(10);
        // 设置第一行 行高
        $sheet->getRowDimension(1)->setRowHeight(20);

        $cellB = $sheet->getCell('B1');
        $cellB->setValue('学科名称');
        $sheet->getColumnDimension('B')->setWidth(10);

        $cellC = $sheet->getCell('C1');
        $cellC->setValue('学生姓名');
        $sheet->getColumnDimension('C')->setWidth(10);

        $cellD = $sheet->getCell('D1');
        $cellD->setValue('成绩');
        $sheet->getColumnDimension('D')->setWidth(10);

        // 设置样式 标题
        $styleArray = [
            'alignment' => [
                'horizontal' => 'center', //水平居中
                'vertical' => 'center', //垂直居中
            ],
            'font' => [
                'name' => '黑体',
                'bold' => false,
                'size' => 10
            ]
        ];
        // 设置样式 正文
        $styleArrayBody = [
            'alignment' => [
                'horizontal' => 'center', //水平居中
                'vertical' => 'center', //垂直居中
            ],
            'font' => [
                'name' => '宋体',
                'bold' => false,
                'size' => 10
            ]
        ];
        // 应用样式
        $sheet->getStyle('A1')->applyFromArray($styleArray);
        $sheet->getStyle('B1')->applyFromArray($styleArray);
        $sheet->getStyle('C1')->applyFromArray($styleArray);
        $sheet->getStyle('D1')->applyFromArray($styleArray);

        // 从 A2 开始填充数据
        // 获取单元格
        $cellA = $sheet->getCell('A2');
        // 设置单元格的值
        $cellA->setValue(1);

        $cellB = $sheet->getCell('B2');
        $cellB->setValue('123456');

        $cellC = $sheet->getCell('C2');
        $cellC->setValue('12345');

        $cellD = $sheet->getCell('D2');
        $cellD->setValue(100);

        // 再给表格体设置样式
        $sheet->getStyle('A2')->applyFromArray($styleArrayBody);
        $sheet->getStyle('B2')->applyFromArray($styleArrayBody);
        $sheet->getStyle('C2')->applyFromArray($styleArrayBody);
        $sheet->getStyle('D2')->applyFromArray($styleArrayBody);


        $file_name = '成绩列表导入模板.xlsx';
        // 实例化导出类
        header('Content-Type:application/vnd.ms-excel');
        header('Content-Disposition:attachment;filename='.$file_name);
        header('Cache-Control:max-age=0');

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
    }
}
